import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getUserFromRequest } from '@/lib/auth'

export async function GET(request: NextRequest) {
  try {
    const user = getUserFromRequest(request)
    
    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    const { searchParams } = new URL(request.url)
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '10')
    const search = searchParams.get('search') || ''

    const skip = (page - 1) * limit

    // 构建查询条件
    const where = search ? {
      OR: [
        { title: { contains: search } },
        { description: { contains: search } },
        { author: { contains: search } }
      ]
    } : {}

    // 获取视频列表和总数
    const [videos, total] = await Promise.all([
      prisma.tikTokVideo.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        skip,
        take: limit,
        include: {
          textExtractions: {
            select: {
              id: true,
              status: true,
              method: true
            }
          }
        }
      }),
      prisma.tikTokVideo.count({ where })
    ])

    return NextResponse.json({
      videos,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit)
      }
    })

  } catch (error) {
    console.error('Get videos error:', error)
    return NextResponse.json(
      { error: '获取视频列表失败' },
      { status: 500 }
    )
  }
}
